package main

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

func main(){
	

	http.HandleFunc("/turn", handleRedirect)
	fmt.Println("Server is running on http://localhost:7766")
	http.ListenAndServe(":7766", nil)
}

func handleRedirect(w http.ResponseWriter,r *http.Request){
	// 创建一个自定义的Transport，并禁用证书验证
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	// 创建一个基于自定义Transport的HTTP客户端
	client := &http.Client{
		Transport: tr,
		
	}
	targetUrl := "https://192.40.10.229/async/login/token/"

	payload:=url.Values{"user":{"account"}, "pwd": {"Lousao@1234!"}}

	response, err := client.PostForm(targetUrl, payload)

	if err!=nil{
		fmt.Printf("错误信息为%v\n",err.Error())
		return
	}

	body,err:=io.ReadAll(response.Body)
	if err!=nil{
		fmt.Printf("读取的错误信息为%v\n",err.Error())
		return
	}
	defer response.Body.Close()
	
	var tmpRes = make(map[string]interface{})

	//解码json到map
	err = json.Unmarshal(body,&tmpRes)
	if err!=nil{
		fmt.Printf("json解析出错，错误信息为%v\n",err.Error())
		return
	}
	
	fmt.Printf("解析成功后的数据为%#v\n",tmpRes["token"])
	tokenStr,err := json.Marshal(tmpRes["token"])
	if err!=nil{
		fmt.Printf("json转化出错，错误信息为%v\n",err.Error())
		return
	}
	// fmt.Printf("转化成功，结果为%#v\n",tokenStr)





	//单点登录
	singleSignOnUrl := "https://192.40.10.229/singleSignOn/"
	// w.Header().Set("token", string(tokenStr))
	// http.Redirect(w,r,singleSignOnUrl,http.StatusSeeOther)
	resp,err := http.NewRequest(http.MethodPost,singleSignOnUrl,nil)
	if err!=nil{
		fmt.Printf("创建失败，失败信息为%v\n",err.Error())
		return
	}
	resp.Header.Set("token",string(tokenStr))
	resp.Header.Set("User-Agent","Apifox/1.0.0 (https://apifox.com)")
	resp.Header.Set("Accept","*/*")
	resp.Header.Set("Accept-Encoding","gzip, deflate, br")
	resp.Header.Set("host","192.40.10.229")
	resp.Header.Set("Connection","keep-alive")

	// 创建一个自定义的Transport，并禁用证书验证
	tr = &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	// 创建一个基于自定义Transport的HTTP客户端
	client = &http.Client{
		Transport: tr,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}	
	
	sessReq,err := client.Do(resp)
	if err!=nil{
		fmt.Printf("发送出错，错误信息为%v\n",err.Error())
		return
	}
	defer sessReq.Body.Close()
	fmt.Printf("请求头数量为%v\n",len(sessReq.Header))
	//打印所有响应头
	for key,values :=range sessReq.Header{
		for _,val := range values{
			fmt.Printf("响应头%s:%s\n",key,val)
		}
	}

	// fmt.Printf("读取成功,结果为%#v\n",sessReq.Header.Values("Set-Cookie"))
	cookies := sessReq.Cookies()
	// fmt.Printf("读取成功,结果为%v\n",cookies)

	// defer sessReq.Body.Close()
	// _,err = io.ReadAll(sessReq.Body)
	// if err!=nil{
	// 	fmt.Printf("读取sessReqBody出错,错误信息为%v\n",err.Error())
	// 	return
	// }
	// fmt.Printf("读取成功,结果为%v\n",sessReqBody)

	//重定向
// 	res.set("host", "192.40.10.229");
//   res.set("origin", "https://192.40.10.229");
//   res.set("referer", "https://192.40.10.229/main/");
//   res.redirect("https://192.40.10.229/main/#/account/usercenter/");
// 帐号:account
// 密码:Lousao@1234!
// 网址:https://192.40.10.229/
	target := "https://192.40.10.229/main/#/account/usercenter/"
	// w.Header().Set("host", "192.40.10.229")
	// w.Header().Set("origin", "https://192.40.10.229")
	// w.Header().Set("referer", "https://192.40.10.229/main/")
	for _,cookie :=range cookies{
		// fmt.Printf("cookie为%#v\n",cookies)
		cookie.Domain="192.40.10.229"
		http.SetCookie(w,cookie)
	}
	cookie1 :=&http.Cookie{
		Name: "sid",
		Value:"a9f4a46682cca8ae23389f36c978ad7f8cd8cb7256075c2f0ffd24b6cb8e5a41bcb7a38da8f7789d3f3391a23f7795a9",
		Path:"/",
		Domain:"192.40.10.229",
		Secure: true,
		SameSite: http.SameSiteNoneMode,
		Expires:time.Now().Add(24*time.Hour),
	}
	http.SetCookie(w,cookie1)
	http.Redirect(w,r,target,http.StatusSeeOther)
}